ENT.Base = "base_point"
ENT.Type = "point"

function ENT:Initialize()
	self.Time = 0
	self.Delay = self:GetKeyValue( "delay", 0 )
	self.SpawnDelay = self:GetKeyValue( "spawndelay", 10 )
	self.Children = {}
end

function ENT:GetChildren()
	local num = 0
	for child, _ in pairs( self.Children ) do
		if ( IsValid( child ) ) then
			num = num + 1
		else
			self.Children[ child ] = nil
		end
	end
	return num
end

function ENT:Think()
	if self.Deactivated then return end
	
	if ( GAMEMODE:IsBuild() ) then return end
	
	local wave = GAMEMODE:GetRoundNumber()
	local first, endwave = self:GetKeyValue ("wave", 1), self:GetKeyValue ("endwave")
	if ( wave < first || ( endwave && wave >= endwave ) ) then return end
	
	self.Time = self.Time + 0.5
	if ( self.Time > self.SpawnDelay + self.Delay ) then
		self.Time = self.Time - self.SpawnDelay
		
		if ( self:GetChildren() < tonumber( self:GetKeyValue( "maxchildren", 10 ) ) ) then
			local npc = ents.Create( self:GetKeyValue( "class", "npc_combine_s" ) )
				npc:SetPos( self:GetPos() )
				npc:SetAngles( self:GetAngles() )
				npc:SetHealth( npc:Health() * self:GetKeyValue( "healthmulti", 1 ) )
				npc:SetKeyValue( "spawnflags", 256 + 512 + 1024 + 8192 + 131072 + self:GetKeyValue( "spawnflags", 0 ) )
				npc:SetKeyValue( "squadname", "squad"..self.Entity:EntIndex() )
				npc:SetKeyValue( "additionalequipment", self:GetKeyValue( "equipment", "" ) )
				npc:SetKeyValue( "NumGrenades", "999" )
				if self:GetKeyValue( "model", false ) then
					npc:SetKeyValue ("model", self:GetKeyValue ("model"))
				end
			npc:Spawn()
			
			local rallypoint = self:GetKeyValue("rallypoint", "rallypoint1")
			timer.Simple (0.1, function()
				if IsValid(npc) then
					npc:Fire("Assault", rallypoint)
				end
			end)
			
			self.Children[ npc ] = true
			
			GAMEMODE:CallHook( "NPCSpawned", npc, self )
		end
	end
	
	self:NextThink( CurTime() + 0.5 )
	return true
end

function ENT:GetNPCClass()
	return self:GetKeyValue( "class", "npc_combine_s" )
end

function ENT:GetKeyValue( key, default )
	if ( !self.KeyValues || !self.KeyValues[ key ] ) then return default end
	return self.KeyValues[ key ]
end
function ENT:KeyValue( key, value )
	self.KeyValues = self.KeyValues or {}
	self.KeyValues[ key ] = tonumber(value) or value
end

function ENT:AcceptInput (name)
	if name == "Enable" then
		self.Deactivated = false
	elseif name == "Disable" then
		self.Deactivated = true
	elseif name == "Toggle" then
		self.Deactivated = !self.Deactivated
	end
end
